/**
 * 用以持久化和获取access token
 */

const KEY_ACCESS_TOKENS = "__access_tokens__";
const KEY_USER = "__user__";

/**
 * 设置当前用户
 * 
 * @param loginUser 当前登录用户
 */
module.exports.setUser = function(loginUser) {
  // 保存当前用户
  wx.setStorageSync(KEY_USER, loginUser)
  // 同时保存access token
  this.setTokens(loginUser);
}

/**
 * 清除当前用户信息
 */
module.exports.clearUserInfo = function () {
  // 
  try {
    wx.removeStorageSync(KEY_ACCESS_TOKENS)
    wx.removeStorageSync(KEY_USER)
  } catch (e) {
  }
  const app = getApp()
  // app.globalData.userInfo = null
  console.log(app.globalData)
}

/**
 * 取得当前用户
 */
module.exports.getUser = function() {
  return wx.getStorageSync(KEY_USER)
}

/**
 * 保存access tokens
 * 
 * @params tokens {
 *  "accessToken": "33333",
 *  "expiresIn": 7200,
 *  "refreshToken": "4444",
 *  "refreshExpiresIn": 14400
 * }，传null表示清空access token
 */
module.exports.setTokens = function (tokens) {
  if (!tokens) {
    this.clearTokens();
    return
  }

  try {    
    wx.setStorageSync(KEY_ACCESS_TOKENS, {
      "accessToken": tokens.accessToken,
      "expiresTo": new Date().getTime() + parseInt(tokens.expiresIn) * 1000,
      "refreshToken": tokens.refreshToken,
      "refreshExpiresTo": new Date().getTime() + parseInt(tokens.refreshExpiresIn) * 1000
    })
  } catch (e) {
  }
}

/**
 * 清除access tokens
 */
module.exports.clearTokens = function () {
  try {
    wx.removeStorageSync({
      key: KEY_ACCESS_TOKENS
    })
  } catch (e) {
  }
}

/**
 * 取得access tokens
 */
module.exports.getTokens = function() {
  return wx.getStorageSync(KEY_ACCESS_TOKENS)
}
